import React, { Fragment, useEffect, useState} from "react";
import { Button,Card, Divider, message, Popconfirm, Table} from "antd";
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import { fileItem } from "./data";
import { ColumnProps } from "antd/lib/table";
import SearchForm from '@/components/SearchForm';
import styles from '@/utils/table.less';
import { PaginationConfig } from "antd/es/pagination";
import { ConnectState, Dispatch } from '@/models/connect';
import encodeQueryParam from "@/utils/encodeParam";
import { connect } from 'dva';
import Save from './add';
import moment from "moment";
import apis from '@/services';
import proxy from "../../../config/proxy";


interface Props {
    loading: boolean;
    dispatch:Dispatch;
    files: any;
    location: Location;
}
interface State {
    data: any;
    searchParam: any;
    saveVisible:boolean;
    currentItem: Partial<fileItem>;
    typeList: any;
    
}
const Files: React.FC<Props> = props => {
    const { dispatch } = props;
    const { result } = props.files;
    const initState: State = {
        searchParam: {
          pageIndex: 0,
          pageSize: 10,
        },
        data: result,
        saveVisible:false,
        currentItem: {},
        typeList:[
            {
                id: 'file',
                name : '文件'
            },
            {
                id:'picture',
                name:'图片'
            },
            {
                id:'video',
                name:'视频'
            },
            {
                id:'music',
                name:'音频'
            }
        ]
      };
    const [searchParam, setSearchParam] = useState(initState.searchParam);
    const [saveVisible, setSaveVisible] = useState(initState.saveVisible);
    const [currentItem, setCurrentItem] = useState(initState.currentItem);
    const [typeList,setTypeList] = useState(initState.typeList);
    const [loading, setLoading] = useState<boolean>(false);

    const handleSearch = (params?: any) => {
        setSearchParam(params);
        dispatch({
            type: 'files/query',
            payload: encodeQueryParam(params)
        });
    };
    const onTableChange = (pagination: PaginationConfig, filters: any, sorter: any) => {
        handleSearch({
          pageIndex: Number(pagination.current) - 1,
          pageSize: pagination.pageSize,
          terms: searchParam.terms,
          sorts: sorter,
        });
    }; 
    useEffect(() => {
        handleSearch(searchParam)
    }, []);
    const saveOrUpdate = (fileValue) => {
        if(!fileValue.id){
            const formData = new FormData();
            formData.append('files', fileValue.files);
            if(fileValue.fileName != undefined){
                formData.append('fileName', fileValue.fileName);
            }
            fetch(proxy.dev['/AllLinks'].target+'/file-manage/save',{
                method: 'post',
                body:formData,
            }).then((data) => {
                console.log(data)
                message.success("添加成功");
                setSaveVisible(false);
                handleSearch(searchParam);
                setCurrentItem({})
            })
        }else{
            let param = {};
            param['id'] = fileValue.id;
            param['fileName'] = fileValue.fileName;
            dispatch({
                type: 'files/update',
                payload: encodeQueryParam(param),
                callback: (response: any) => {
                    if (response.status === 200) {
                        message.success("修改成功");
                        setSaveVisible(false);
                        handleSearch(searchParam);
                        setCurrentItem({})
                    } 
                }
            })
        }
    };
    const edit = (record: fileItem) => {
        setCurrentItem(record);
        setSaveVisible(true);
    };
    const conditions = (params:any) => {
        if(params){
            params.pageSize = 10;
            params.pageIndex = 0;
            handleSearch(params);
        }else{
            let list:any = [];
            list.pageSize = 10;
            list.pageIndex = 0;
            handleSearch(list);
        }
    };
    const handleDelete = (item: any) => {
        apis.files.remove(item.id)
          .then((response: any) => {
            if (response.status === 200) {
              message.success('删除成功');
              handleSearch(searchParam);
            }
          })
          .catch(() => {
          });
    };
    const exportFile = (item: any) => {
        const w = window.open('about:blank');
        w.location.href = item.filePath; 
    };
    const columns : ColumnProps<fileItem>[]= [
        {
            title: '文件名称',
            dataIndex: 'fileName',
            width: '200px',
        },
        {
            title: '文件类型',
            dataIndex: 'fileType',
            width: '110px',
            render: text =>
            text === 'picture' ? '图片' : (text === 'picture' ? '图片' :(text === 'video' ? '视频' :(text === 'file' ? '文件' : '音频'))),
        },
        {
            title:'文件路径',
            dataIndex: 'filePath',
        },
        // {
        //     title: '文件图片',
        //     render: (text,record) =>(
        //         <Fragment>
        //             {
        //                 record.fileType === 'picture'?
        //                 <Fragment>
        //                      <img height="70" src={record.filePath}/>
        //                 </Fragment>: ''
        //             }
        //         </Fragment>
        //     )
        // },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: '170px',
            render:(text) => (
                <Fragment>
                    {
                        moment(text).format('YYYY-MM-DD HH:mm')
                    }
                </Fragment>
            )
        },
        {
            title:'修改时间',
            dataIndex:'modifyTime',
            width: '170px',
            render:(text) => (
                <Fragment>
                    {
                        moment(text).format('YYYY-MM-DD HH:mm')
                    }
                </Fragment>
            )
        },
        {
            title:'操作',
            align: 'center',
            width: '150px',
            fixed: 'right',
            render: (text, record) => (
                <Fragment>
                    <a onClick={() => edit(record)}>编辑</a>
                    <Divider type="vertical" />
                    <a onClick={() => exportFile(record)}>下载</a>
                    <Divider type="vertical" />
                    <Popconfirm
                        title="确认删除此文件吗？"
                        onConfirm={() => {
                        setLoading(true);
                        handleDelete(record);
                        }}
                    >
                        <a>删除</a>
                    </Popconfirm>
                </Fragment>
            ),
        }
    ];
    return (
            <PageHeaderWrapper title="文件管理">
                <Card bordered={false} style={{ marginBottom: 16 }}>
                    <div>
                        <SearchForm
                            search={(params: any) => {
                                setSearchParam(params)
                                conditions(params)
                            }}
                            formItems={[
                                {
                                    label: "文件名称",
                                    key: "fileName",
                                    type: 'string'
                                },
                                {
                                    label: "文件类型",
                                    key: "fileType",
                                    type: 'list',
                                    props: {
                                        data: typeList,
                                        mode: 'fileType',
                                      }
                                },
                            ]}
                        />
                    </div>
                    <div className={styles.tableListOperator}>
                        <Button  icon="plus" type="primary" onClick={()=>{ setSaveVisible(true) }}>新建</Button>
                    </div>
                </Card>
                <Card bordered={false}>
                    <Table
                        loading={props.loading}
                        dataSource={(result || {}).data}
                        columns={columns}
                        rowKey="id"
                        scroll={{ x: 1300 }}
                        onChange={onTableChange}
                        pagination={{
                            current: result.pageIndex + 1,
                            total: result.total,
                            pageSize: result.pageSize,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSizeOptions: ['10', '20', '50', '100'],
                            showTotal: (total: number) => `共 ${total} 条记录 第  ${result.pageIndex + 1}/${Math.ceil(result.total / result.pageSize)}页`
                        }}
                    />
                </Card>
                {
                    saveVisible &&
                    <Save
                        data={currentItem}
                        close={() => { setSaveVisible(false); setCurrentItem({}) }}
                        save={(files: fileItem) => { saveOrUpdate(files) }}
                    />
                }
            </PageHeaderWrapper>
    )
};
export default connect(({ files, loading }: ConnectState) => ({
    files,
    loading: loading.models.files
}))(Files)